import { Component, ElementRef, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { HttpModule } from '@angular/http';
import { HttpClientModule, HttpClient, HttpErrorResponse } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { RouterModule, Router, ActivatedRoute } from '@angular/router';

import { Service } from '../../../server/server';
import { RoleComponent } from '../role.component';
import { HintsService } from '../../../public/serve/hints/hints.service';
declare var $: any;

interface rolesResponse {
  result: string[];
  result_code: string;
  message: string;
}
export class roleaddtype {
  roleGroupName: string;
  description: string;
  roleName: string;
  autoAssignment: boolean;
  roleCode: string;
}

@Component({
  selector: 'app-role-add',
  templateUrl: './role-add.component.html',
})
export class RoleAddComponent implements OnInit {

  constructor(
    private http: HttpClient, 
    private router: Router, 
    private server: Service, 
    private rolecomponent: RoleComponent,
    private hintsService:HintsService
  ) {
    //接受角色组数据
    this.rolesdataeeventEmit = this.server.rolesdataeeventEmit.subscribe((value: any) => {
      //console.log(this.roleadddata)
      this.roleadddata = value;
      this.default();
    });
  }

  //取消订阅
  public rolesdataeeventEmit: any;
  ngOnDestroy() {
    if (this.rolesdataeeventEmit) {
      this.rolesdataeeventEmit.unsubscribe();
    }
  }

  @Input() roleadddata: object;

  @Output()
  addOutput: EventEmitter<any> = new EventEmitter();
  //清空
  @ViewChild('newlyAddedForm') formElement: HTMLFormElement;

  reset() {
    $("#add").modal("hide");
    this.formElement.reset();
    setTimeout(() => {
      this.roleadd.autoAssignment = false;
      this.default();
    }, 300);
  }

  //默认数据
  default() {
    this.roleadd.roleGroupName = this.roleadddata[0].roleGroupId;
  }

  //datatype
  roleadd: roleaddtype = {
    roleGroupName: '',
    description: '',
    roleName: '',
    autoAssignment: false,
    roleCode: ''
  };
  //用户id
  createUserId: any;
  stringnull: any = null || '';
  //roleslist
  ngOnInit() {
    this.createUserId = this.server.getuser();
  }

  test(e) {
    //console.log(e)
  }
  //role add
  add(): void {
    let body = {
      roleName: this.roleadd.roleName,
      roleGroupId: this.roleadd.roleGroupName,
      description: this.roleadd.description,
      autoAssignment: Number(this.roleadd.autoAssignment),
      createUserId: this.createUserId,
      roldCode: this.roleadd.roleCode
    };
    //console.log(body)
    this.http.post<rolesResponse>(this.server.baseUrl+'admin/roles/add', body)
      .subscribe(res => {
        this.addOutput.emit(res.result_code);
        //console.log(res)
        this.hintsService.messages(res.message,res.result_code);
        if (res.result_code === '0000') {
          //console.log("添加成功");
          this.reset();
          //prompt

        }
      });
  }

}
